$j=jQuery.noConflict();
$j(document).ready(function()
{	$j("#tableForm").trigger('reset');	colType();
	loadPicture();
	addCol();
	addRow();
	$j("textarea").jGrow({ rows: 25 });
	newTable();
	checkInput();
	cityCheckBox();
	$j("#showHiddenInfo").click(function()
	{
		$j("#hiddenInfo").slideDown(300);
		$j(this).slideUp(300);
		$j("#hideHiddenInfo").click(function()
		{
			$j("#hiddenInfo").slideUp(300);
			$j("#showHiddenInfo").slideDown(300);
		});
	});
	$j("#tableForm").submit(function()
	{
		var checkBox=false;
		$j(".cityCheckBox").each(function(event)
		{
			if($j(this).prop("checked"))
				checkBox=true;
		});
		if(!checkBox && $j(".cityCheckBox").attr('class')=='cityCheckBox')
		{
			alert('Выберите минимум один город!');
			return false;
		}
	});});
function cityCheckBox()
{
	$j("#showCities").click(function()
	{
		$j("#cities").slideToggle(300);
	});
	$j(".cityCheckBox").change(function(event)
	{
		$j(".allCities").prop('checked', true);
		$j(".cityCheckBox").each(function(event)
		{
			if(!$j(this).prop("checked"))
				$j(".allCities").prop('checked', false);

		});
	});
	$j(".allCities").change(function()
	{

		if(!$j(".allCities").prop('checked'))
		{
			$j(".cityCheckBox").removeAttr("checked");
			$j("#cities").slideDown(300);
		}
		else
		{
			$j(".cityCheckBox").attr("checked", "checked");
			$j(".cityCheckBox").prop("checked", true);
			//$j("#cities").slideUp(300);
		}
	});
}
function checkInput()
{	$j("textarea").keyup(function(event)
	{		if($j(this).val().length>200)
		{			alert('Максимум 200 символов!');
			$j(this).val($j(this).val().substr(0, 200));
		}	});
	$j("#tabName").keyup(function(event)
	{
		if($j(this).val().length>20)
		{
			alert('Максимум 20 символов!');
			$j(this).val($j(this).val().substr(0, 20));
		}
	});
	$j(".tblNameInput").keyup(function(event)
	{
		if($j(this).val().length>50)
		{
			alert('Максимум 50 символов!');
			$j(this).val($j(this).val().substr(0, 60));
		}
	});}
function colType()
{	$j(".colType").unbind("change");	$j(".colType").change(function(event)
	{		var temp=$j("#temp").val();		var type=$j(this).val();
		var row=parseInt($j(this).attr("id").substr(8));
		var table=$j(this).attr("id").substr(7).substr(0, 1);
		var rowNum=parseInt($j("#table"+table+" tr").length)-3;
		var check=false;
		for(var i=11; i<=(rowNum+10); i++)
		{
			if($j("textarea[name='"+table+""+i+""+row+"']").val())check=true;
			if($j("#span"+table+""+i+""+row).html()=="Изменить")check=true;
		}
		if(check)
		{			if(!confirm('Внимание, изменив тип столбца, вы потеряете несохраненные данные!'))return;		}
		for(var i=11; i<=(rowNum+10); i++)
		{			var id=table+""+i+""+row;			$j("#"+table+""+i+""+row).attr("class", type);
			if(type=="img")
			{				var html='\
				<div id="upload'+id+'" class="upload">\
	 				<span id="span'+id+'" class="loadButton" imgName="'+temp+''+id+'">Загрузить</span>\
	 			</div>\
	 			<div id="preview'+id+'" class="preview">\
  	 				<span id="status'+id+'"></span>\
	    		</div>';				$j("#"+table+""+i+""+row).html(html);			}
			else if(type=="noType")
				$j("#"+table+""+i+""+row).html('');
			else
				$j("#"+table+""+i+""+row).html('<textarea name="'+table+''+i+''+row+'"></textarea>');		}
		loadPicture();
		$j("textarea").jGrow({ rows: 25 });
		$j(".noType").unbind('click');
		$j(".noType").click(function()
		{
			if($j(this).attr('class')=='noType')alert('Выберите тип данных столбца!');
		});
		checkInput();	});}
function loadPicture()
{	$j(".loadButton").unbind("click");	$j(".loadButton").click(function(event)
	{		var temp=$j("#temp").val();		var id=$j(this).attr("id").substr(4);
		var imgName=$j(this).attr("imgName");
		var btnUpload=jQuery('#upload'+id);
		var status=jQuery('#status'+id);
		new AjaxUpload(btnUpload,
		{
			action: 'actions/loadAvatar.php',
			name: 'pictures/temp/'+imgName,
			onSubmit: function(file, ext)
			{
				//$j("#preview").html('');
				if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext)))
				{
					$j('#preview img').remove();
					status.text('Поддерживаемые форматы JPG, PNG или GIF');
					return false;
				}
				status.text('Загрузка...');
			},
			onComplete: function(file, response)
			{
				status.text('');
				if(response)
				{
					$j('#preview'+id+' img').remove();
					$j('#deleteDiv'+id).remove();
					jQuery('#preview'+id).append(response);
                    $j('#preview'+id+' input').attr('name', id);
                    var newLoad='<span id="span'+id+'" class="loadButton" imgName="temp'+temp+''+id+'">Изменить</span>';
                    $j('#preview'+id).append('<div id="deleteDiv'+id+'" class="deleteDiv"><span id="delete'+id+'" class="deleteButton">Удалить</span></div>');
                    $j("#upload"+id).html(newLoad);
                    $j("#upload"+id).css("display", "none");
                    $j("#deleteDiv"+id).css("display", "none");
                    //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!11111111111
                    loadPicture();
                    $j('#preview'+id+' img').click(function()
                    {                    	$j('#preview'+id+' img').css("display", "none");
                    	$j("#upload"+id).css("display", "block");
                    	$j("#deleteDiv"+id).css("display", "block");                    });
                    $j("#delete"+id).click(function()
                    {                    	$j("#preview"+id).html('<span id="status'+id+'"></span>');
                    	$j("#upload"+id).html('<span id="span'+id+'" class="loadButton" imgName="temp'+temp+''+id+'">Загрузить</span>');
    					//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                    	loadPicture();                    });
				}
				else
				{
					jQuery('#preview'+id).style.display='block';
					jQuery('#preview'+id).appendTo('#avatar').text(file).addClass('error');
				}
			}
		});
	});}
function addCol()
{	$j(".addColButton").unbind("click");	$j(".addColButton").one("click", function(event)
	{		var tdId=$j(this).attr("id");
		var tdNum=$j(this).attr("id").substr(3);
		var newTdNum=parseInt(tdNum)+1;		var trId=$j(this).parent().attr("id");
		var trNum=$j(this).parent().attr("id").substr(1);
		var table=tdId.substr(0, 1);
		var rowNum=parseInt($j('#table'+table+' tr').length)-3;
		var newColTypeForm='\
		<select size="1" class="colType" id="colType'+table+''+tdNum+'" name="colType'+table+''+tdNum+'">\
			<option value="noType">Выберите тип</option>\
 				<option value="img">Изображение</option>\
 				<option value="name">Наименование</option>\
 				<option value="brend">Марка</option>\
 				<option value="model">Модель</option>\
 				<option value="about">Описание</option>\
 				<option value="price">Цена</option>\
		</select>';
		var newHeaderForm='<input name="header'+table+''+tdNum+'" type="text" value="">';
		if(tdNum<5)
		{
			$j("#none"+table+'1'+tdNum).html(newColTypeForm);
			$j("#none"+table+'1'+tdNum).attr("class", "colTypeTd");
			$j("#none"+table+'1'+tdNum).attr("id", 'colTypeTd'+table+''+tdNum);
			$j("#colTypeTr"+table).append('<td id="none'+table+'1'+newTdNum+'" class="none">');
			$j("#none"+table+'2'+tdNum).html(newHeaderForm);
			$j("#none"+table+'2'+tdNum).attr("class", 'headerTd');
			$j("#none"+table+'2'+tdNum).attr("id", 'headerTd'+table+''+tdNum);
			$j("#headerTr"+table).append('<td id="none'+table+'2'+newTdNum+'" class="none">');
			for(var i=11; i<=(rowNum+10); i++)
			{				$j("#"+table+""+i).append('<td id="'+table+''+i+''+newTdNum+'"></td>');
				$j('#'+table+''+i+''+tdNum).html('').attr("class", "noType");
				if(i==11)
				{					$j('#'+table+''+i+''+newTdNum).attr("class", "addColButton");
					$j('#'+table+''+i+''+newTdNum).html("Добавить столбец");
				}
				else
					$j('#'+table+''+i+''+newTdNum).attr("class", "add");			}
			$j("#"+table+""+i).append('\
			<td id="'+table+''+i+''+newTdNum+'" class="add">\
			</td>');
		}
		if(tdNum==5)
		{			$j("#none"+table+'1'+tdNum).html(newColTypeForm);
			$j("#none"+table+'1'+tdNum).attr("class", "colTypeTd");
			$j("#none"+table+'1'+tdNum).attr("id", 'colTypeTd'+table+''+tdNum);
			$j("#none"+table+'2'+tdNum).html(newHeaderForm);
			$j("#none"+table+'2'+tdNum).attr("class", 'headerTd');
			$j("#none"+table+'2'+tdNum).attr("id", 'headerTd'+table+''+tdNum);
			for(var i=11; i<=(rowNum+10); i++)
			{
				$j('#'+table+''+i+''+tdNum).html('').attr("class", "noType");
			}		}
		$j(".noType").unbind('click');
		$j(".noType").click(function()
		{			if($j(this).attr('class')=='noType')alert('Выберите тип данных столбца!');
		});
		addCol();
		colType();
		$j("textarea").jGrow({ rows: 25 });
		var colNum=parseInt($j("#colNum"+table).val())+1;
		$j("#colNum"+table).val(colNum);	});}
function addRow()
{	$j(".addRowButton").unbind("click");	$j(".addRowButton").one("click", function(event)
	{		var temp=$j("#temp").val();		var tdId=$j(this).attr("id");
		var tdNum=$j(this).attr("id").substr(3);
		var trId=$j(this).parent().attr("id");
		var trNum=$j(this).parent().attr("id").substr(1);
		var table=tdId.substr(0, 1);
		var newTrNum=parseInt(trNum)+1;
		var newTrId=table+""+newTrNum;
		var colNum=parseInt($j('#'+trId+' td').length);
		$j(this).parent().parent().append('<tr id="'+newTrId+'"></tr>');
		for(var i=1; i<=colNum; i++)
		{			$j("#"+newTrId).append('<td id="'+newTrId+''+i+'"></td>');
			var colType=$j("#colType"+table+''+i).val();
			$j('#'+trId+''+i).attr("class", colType);
			if(colType=='img')
			{				var html='\
				<div id="upload'+trId+''+i+'" class="upload">\
	 				<span id="span'+trId+''+i+'" class="loadButton" imgName="'+temp+''+trId+''+i+'">Загрузить</span>\
	 			</div>\
	 			<div id="preview'+trId+''+i+'" class="preview">\
  	 				<span id="status'+trId+''+i+'"></span>\
	    		</div>';
			}
			else if(colType=='noType')
				var html='';
			else				var html='<textarea name="'+trId+''+i+'"></textarea>';
			var activColNum=$j("#headerTr"+table+" td.headerTd").length;
			if(i<=activColNum)$j('#'+trId+''+i).html(html);

			if(i==1)
			{
				$j('#'+newTrId+''+i).attr("class", "addRowButton");
					$j('#'+newTrId+''+i).html("Добавить ряд");
			}
			else
				$j('#'+newTrId+''+i).attr("class", "add");		}
		addRow();
		loadPicture();
		$j(".noType").unbind('click');
		$j(".noType").click(function()
		{
			if($j(this).attr('class')=='noType')alert('Выберите тип данных столбца!');
		});
		$j("textarea").jGrow({ rows: 25 });
		var rowNum=parseInt($j("#rowNum"+table).val())+1;
		$j("#rowNum"+table).val(rowNum);
		checkInput();	});}
$j.fn.jGrow = function(options) {
      var opts = $j.extend({}, $j.fn.jGrow.defaults, options);
      return this.each(function() {
          $j(this).css({ overflow: "hidden" }).bind("keypress", function() {
              $this = $j(this);
              var o = $j.meta ? $j.extend({}, opts, $this.data()) : opts;
              if(o.rows == 0 && (this.scrollHeight > this.clientHeight)) {
                  this.rows += 1;
              } else if((this.rows <= o.rows) && (this.scrollHeight > this.clientHeight)) {
                  this.rows += 1;
              } else if(o.rows != 0 && this.rows > o.rows) {
                  $this.css({ overflow: "auto" });
              }
              $this.html();
          });
      });
    }
$j.fn.jGrow.defaults = { rows: 0 };
function newTable()
{	$j(".addButton").click(function(event)
	{		var table=$j(this).attr("id").substr(3);
		var temp=$j("#temp").val();
		var newTableNum=parseInt(table)+1;
		var newTableHtml='\
		<div class="aTable">\
		<center>\
		Название таблицы:<br />\
		<input name="tblName'+table+'" class="tblNameInput" type="text" value=""><br /><br />\
		Показывать границы таблицы<input name="border'+table+'" type="checkbox" value="ON"><br /><br />\
		<input name="colNum'+table+'" id="colNum'+table+'" type="hidden" value="3">\
		<input name="rowNum'+table+'" id="rowNum'+table+'" type="hidden" value="2">\
		<input name="countTabs[]" type="hidden" value="'+table+'">\
		<table class="priceTable" id="table'+table+'" border="0" cellspacing="0">\
			<tr id="colTypeTr'+table+'" class="colTypeTr">\
				<td id="colTypeTd'+table+'1" class="colTypeTd">\
					<select size="1" class="colType" id="colType'+table+'1" name="colType'+table+'1">\
						<option value="noType">Выберите тип</option>\
		  				<option value="img" selected>Изображение</option>\
		  				<option value="name">Наименование</option>\
		  				<option value="brend">Марка</option>\
		  				<option value="model">Модель</option>\
		  				<option value="about">Описание</option>\
		  				<option value="price">Цена</option>\
					</select>\
				</td>\
				<td id="colTypeTd'+table+'2" class="colTypeTd">\
					<select size="1" class="colType" id="colType'+table+'2" name="colType'+table+'2">\
		  				<option value="noType">Выберите тип</option>\
		  				<option value="img">Изображение</option>\
		  				<option value="name">Наименование</option>\
		  				<option value="brend">Марка</option>\
		  				<option value="model" selected>Модель</option>\
		  				<option value="about">Описание</option>\
		  				<option value="price">Цена</option>\
					</select>\
				</td>\
				<td id="colTypeTd'+table+'3" class="colTypeTd">\
					<select size="1" class="colType" id="colType'+table+'3" name="colType'+table+'3">\
		  				<option value="noType">Выберите тип</option>\
		  				<option value="img">Изображение</option>\
		  				<option value="name">Наименование</option>\
		  				<option value="brend">Марка</option>\
		  				<option value="model">Модель</option>\
		  				<option value="about">Описание</option>\
		  				<option value="price" selected>Цена</option>\
					</select>\
				</td>\
				<td id="none'+table+'14" class="none">\
				</td>\
			</tr>\
			<tr id="headerTr'+table+'" class="headerTr">\
				<td id="headerTd'+table+'1" class="headerTd">\
					<input name="header'+table+'1" type="text" value="">\
				</td>\
				<td id="headerTd'+table+'2" class="headerTd">\
					<input name="header'+table+'2" type="text" value="">\
				</td>\
				<td id="headerTd'+table+'3" class="headerTd">\
					<input name="header'+table+'3" type="text" value="">\
				</td>\
				<td id="none'+table+'24" class="none">\
				</td>\
			</tr>\
			<tr id="'+table+'11">\
				<td id="'+table+'111" class="img">\
					<div id="upload'+table+'111" class="upload">\
			 			<span id="span'+table+'111" class="loadButton" imgName="'+temp+''+table+'111">Загрузить</span>\
			 		</div>\
			 		<div id="preview'+table+'111" class="preview">\
		  	 				<span id="status'+table+'111"></span>\
			    	</div>\
				</td>\
				<td id="'+table+'112" class="model">\
					<textarea name="'+table+'112"></textarea>\
				</td>\
				<td id="'+table+'113" class="price">\
					<textarea name="'+table+'113"></textarea>\
				</td>\
				<td id="'+table+'114" class="addColButton">\
					Добавить столбец\
				</td>\
			</tr>\
			<tr id="'+table+'12">\
				<td id="'+table+'121" class="img">\
					<div id="upload'+table+'121" class="upload">\
			 			<span id="span'+table+'121" class="loadButton" imgName="'+temp+''+table+'121">Загрузить</span>\
			 		</div>\
			 		<div id="preview'+table+'121" class="preview">\
		  	 				<span id="status'+table+'121"></span>\
			    	</div>\
				</td>\
				<td id="'+table+'122" class="model">\
					<textarea name="'+table+'122"></textarea>\
				</td>\
				<td id="'+table+'123" class="price">\
					<textarea name="'+table+'123"></textarea>\
				</td>\
				<td id="'+table+'124" class="add">\
				</td>\
			</tr>\
			<tr id="'+table+'13">\
				<td id="'+table+'131" class="addRowButton">\
					Добавить ряд\
				</td>\
				<td id="'+table+'132" class="add">\
				</td>\
				<td id="'+table+'133" class="add">\
				</td>\
				<td id="'+table+'134" class="add">\
				</td>\
			</tr>\
		</table>\
		<div class="addButton" id="add'+newTableNum+'">Создать еще таблицу</div>\
		</center>\
		</div>';
		//$j(this).parent().parent().parent().append(newTableHtml);
		$j(".submitButton").before(newTableHtml);
		$j(this).remove();
		colType();
		loadPicture();
		addCol();
		addRow();
		$j("textarea").jGrow({ rows: 25 });
		newTable();
		checkInput();	});}